package com.schoolCommunity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.schoolCommunity.ov.OvSearchConfessionWall;
import com.schoolCommunity.entity.ConfessionWall;
import com.schoolCommunity.entity.ConfessionWallMessage;
import com.schoolCommunity.entity.Information;
import com.schoolCommunity.mapper.ConfessionWallMapper;
import com.schoolCommunity.mapper.ConfessionWallMessageMapper;
import com.schoolCommunity.service.ConfessionWallService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolCommunity.util.CheckInsertConfessionWall;
import com.schoolCommunity.util.InsertES;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author YTH
 * @since 2020-09-09
 */
@Service
public class ConfessionWallServiceImpl extends ServiceImpl<ConfessionWallMapper, ConfessionWall> implements ConfessionWallService {

    @Resource
    private ConfessionWallMapper ConfessionWallMapper;
    @Autowired
    private CheckInsertConfessionWall CheckInsertConfessionWall;
    @Autowired
    private com.schoolCommunity.util.ConfessionWallRedis ConfessionWallRedis;
    @Resource
    private ConfessionWallMessageMapper ConfessionWallMessageMapper;
    @Autowired
    private ConfessionWallService ConfessionWallService;
    @Autowired
    private InsertES insertES;

    Logger log = Logger.getLogger(ConfessionWallServiceImpl.class);

    //添加表白墙
    @Override
    public Information InsertConfessionWall(ConfessionWall ConfessionWall) {

        Information information = new Information();

        //校验数据
        String CheckInsertConfessionWallResult = CheckInsertConfessionWall.checkInsertConfessionWall(ConfessionWall);

        if (CheckInsertConfessionWallResult.equals("数据安全")) {
            //写入数据
            try {
                ConfessionWall.setTime(new Date());
                int insert = ConfessionWallMapper.insertConfessionWall(ConfessionWall);
                if (insert != 0) {
                    //使用返回的id查询数据？需要？
                    //写入到ES中
                    insertES.InsertConfessionWall(ConfessionWall);
                    information.setCode(200).setMessage("表白墙添加成功");

                } else {
                    information.setCode(404).setMessage("表白墙添加失败，请重试");
                }
            } catch (Exception e) {
                information.setMessage("数据写入出错").setCode(404);
                return information;
            }

        } else {

            information.setMessage(CheckInsertConfessionWallResult).setCode(404);

        }
        return information;

    }

    //获取所有表白墙，管理者功能
    @Override
    public Information getAllConfessionWallForAdmin() {

        Information Information = new Information();

        try {

            List<ConfessionWall> confessionWalls = ConfessionWallMapper.selectList(null);
            if (!confessionWalls.isEmpty()) {
                Information.setMessage("所有表白墙获取成功").setCode(200).setData(confessionWalls);
            } else {
                Information.setCode(404).setMessage("所有表白墙获取失败");
            }

        } catch (Exception e) {
            Information.setCode(404).setMessage("查询发生错误，请重试");
            return Information;
        }


        return Information;
    }

    //获取所有未通过审核的表白墙，管理者功能
    @Override
    public Information getNotPassConfessionWall() {

        Information Information = new Information();

        try {

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("Suggest", 2);

            List<ConfessionWall> confessionWalls = ConfessionWallMapper.selectList(queryWrapper);
            if (!confessionWalls.isEmpty()) {

                Information.setMessage("获取所有未通过审核的表白墙成功").setCode(200).setData(confessionWalls);
            } else {
                Information.setCode(404).setMessage("获取所有未通过审核的表白墙失败,暂无数据");
            }
        } catch (Exception e) {
            Information.setCode(404).setMessage("查询发生错误，请重试");
            return Information;
        }
        return Information;

    }

    //获取尚未审核的表白墙
    @Override
    public Information getNotSuggestConfessionWall() {
        Information Information = new Information();

        try {

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("Suggest", 0);

            List<ConfessionWall> confessionWalls = ConfessionWallMapper.selectList(queryWrapper);
            if (!confessionWalls.isEmpty()) {

                Information.setMessage("获取所有未通过审核的表白墙成功").setCode(200).setData(confessionWalls);
            } else {
                Information.setCode(404).setMessage("获取所有未通过审核的表白墙失败");
            }
        } catch (Exception e) {
            Information.setCode(404).setMessage("查询发生错误，请重试");
            return Information;
        }
        return Information;
    }

    //管理员审核某一条表白墙
    @Override
    public Information AdminSuggestConfessionWall(long ConfessionWallId, int suggestResult) {

        Information information = new Information();

        QueryWrapper QueryWrapper = new QueryWrapper();
        QueryWrapper.eq("id", ConfessionWallId);

        int update = ConfessionWallMapper.update(new ConfessionWall().setSuggest(suggestResult), QueryWrapper);

        if (update != 0) {
            information.setMessage("用户表白墙审批成功").setCode(200);
        } else {
            information.setMessage("用户表白墙审批失败").setCode(404);
        }
        return information;
    }

    //管理员发布表白墙。实际上批量修改periods字段
    @Override
    public Information AdminPublishConfessionWall(int[] pushList) {

        Information information = new Information();

        int maxPeriods = ConfessionWallService.getMaxPeriods();
        int result = 0;
        for (int i = 0; i < pushList.length; i++) {

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", pushList[i]);

            int update = ConfessionWallMapper.update(new ConfessionWall().setPeriods(maxPeriods + 1), queryWrapper);

            result += update;
        }

        information.setMessage("一共有" + result + "条表白墙被发布").setCode(200);

        return information;
    }


    //获取所有表白墙，管理者功能
    @Override
    public Information getAllConfessionWall() {

        Information Information = new Information();

        try {
            //用户端获取所有通过审核的
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("Suggest", 1);
            queryWrapper.select("id", "text", "time", "member_id", "member_nickname", "show_nickname", "loves", "Suggest", "title", "periods");


            List<ConfessionWall> confessionWalls = ConfessionWallMapper.selectList(queryWrapper);
            if (!confessionWalls.isEmpty()) {
                Information.setMessage("所有表白墙获取成功").setCode(200).setData(confessionWalls);
            } else {
                Information.setCode(404).setMessage("所有表白墙获取失败");
            }

        } catch (Exception e) {
            Information.setCode(404).setMessage("查询发生错误，请重试");
            return Information;
        }


        return Information;
    }

    //删除表白墙，同时删除对应留言。
    @Override
    public Information deleteConfessionWall(long confessionWallId) {
        Information Information = new Information();

        int i = ConfessionWallMapper.deleteById(confessionWallId);

        if (i != 0) {
            log.info("表白墙删除成功，现在删除对应的留言");
            Information.setCode(200).setMessage("表白墙删除成功");
            //根据这个id获取对应的留言id

            //获取与该表白墙相应的留言对象
            QueryWrapper QueryWrapper = new QueryWrapper();
            QueryWrapper.select("id");
            QueryWrapper.eq("confession_wall_id", confessionWallId);
            List<ConfessionWallMessage> list = ConfessionWallMessageMapper.selectList(QueryWrapper);
            int deleteResult = 0;
            for (int k = 0; k < list.size(); k++) {
                ConfessionWallMessageMapper.deleteById(list.get(k).getId());
                deleteResult++;
            }
            log.info("一共删除了" + deleteResult + "条留言");


        } else {
            Information.setCode(404).setMessage("表白墙删除失败");
        }

        return Information;
    }

    //获取指定期数的表白墙,默认最大
    @Override
    public Information getPeriodsConfessionWall(long periods) {

        Information information = new Information();

        if (periods == 0)   //获取到最大期数
            periods = ConfessionWallMapper.getMaxPeriods();


//        List<ConfessionWall> appointConfessionWallRedis = ConfessionWallRedis.getAppointConfessionWallRedis(periods);
//        if (appointConfessionWallRedis == null) {  //判断如果从redis获取的数据为空，则开始从数据读取，并写入redis
//            log.info("redis中读取了到了第" + periods + "期的表白墙数据为NULL");

            //从数据库获取数据
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("periods", periods);
            queryWrapper.eq("Suggest", 1);
            queryWrapper.select("id", "text", "time", "member_id", "member_nickname", "show_nickname", "loves", "Suggest", "title", "periods");

            List list = ConfessionWallMapper.selectList(queryWrapper);

            if (list.isEmpty()) {
                information.setMessage("这期表白墙还没有数据哦").setCode(404);
            } else { //判断这期表白墙数据库存在数据，写入redis
//                boolean b = ConfessionWallRedis.setAppointConfessionWallRedis(list, periods);
//                log.info("redis中写入第" + periods + "期的表白墙结果是：" + b);
                information.setMessage("获取第" + periods + "期表白墙成功").setCode(200).setData(list);
            }

//        } else {
//            log.info("redis中读取了到了第" + periods + "期的表白墙数据，直接返回输出");
//            information.setMessage("获取第" + periods + "期表白墙成功").setCode(200).setData(appointConfessionWallRedis);
//        }
        return information;
    }

    //获取指定用户的表白墙
    @Override
    public Information getMemberConfessionWall(long memberId) {

        Information information = new Information();

        //先从redis读取
//        List<ConfessionWall> memberConfessionWall = ConfessionWallRedis.getMemberConfessionWall(memberId);
//        if(memberConfessionWall==null){
//            log.info("redis找不到用户id为"+memberId+"的数据，开始从数据库读取并写入");

        //从数据库获取指定用户的表白墙数据
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("member_id", memberId);
        queryWrapper.select("id", "text", "time", "member_id", "member_nickname", "show_nickname", "loves", "Suggest", "title", "periods");

        List list = ConfessionWallMapper.selectList(queryWrapper);
        if (list.isEmpty()) {
            information.setMessage("这个用户并没有写表白墙").setCode(404);
        } else {
//                log.info("从数据库找到了用户id为"+memberId+"的数据，写入redis，并直接返回数据");
//                boolean b = ConfessionWallRedis.setMemberConfessionWall(list, memberId);
//                log.info("写入redis的结果为"+b);
            information.setMessage("获取ID为" + memberId + "的用户的表白墙成功").setCode(200).setData(list);
        }

//        }else{
//            log.info("redis找到了用户id为"+memberId+"的数据，直接返回数据");
//            information.setMessage("获取ID为"+memberId+"的用户的表白墙成功").setCode(200).setData(memberConfessionWall);
//        }


        return information;
    }

    //获取最大表白墙期数
    @Override
    public int getMaxPeriods() {

        //最大期数放入redis，设置一天，以后管理员更新期数要注意实时更新最大期数
//        Object maxPeriods = ConfessionWallRedis.getMaxPeriods();
//        if(maxPeriods==null){
//            log.info("redis中没有检测到最大期数，开始从数据库获取最大期数");
        Integer maxPeriodsSQL = ConfessionWallMapper.getMaxPeriods();
//            log.info("获取到最大期数是"+maxPeriodsSQL+"开始写入redis");
//            boolean b = ConfessionWallRedis.setMaxPeriods(maxPeriodsSQL);
//            if(b){
//                log.info("redis写入最大期数成功");
//            }
//            else{
//                log.info("redis写入最大期数失败");
//            }
        return maxPeriodsSQL;
//        }else{
//            log.info("redis中存在最大期数数据"+(int)maxPeriods+"即将返回");
//            return (int)maxPeriods;
//
//        }


    }

    //用户点赞表白墙
    @Override
    public Information AddLoves(long confessionWallId, long memberId) {

        Information information = new Information();

        if (ConfessionWallRedis.getMemberAddLoves(confessionWallId, memberId)) {
            log.info("此人一天内点赞过");
            information.setCode(404).setMessage("一天内只能点赞一次");
        } else {

            log.info("点赞直接写入数据库");
            Integer integer = ConfessionWallMapper.AddLoves(confessionWallId);
            if (integer == 1) {

                ConfessionWallRedis.setMemberAddLoves(confessionWallId, memberId);
                information.setMessage("点赞成功").setCode(200);

            } else {
                information.setCode(404).setMessage("点赞失败");
            }

        }
        return information;
    }

    //尚未实现搜索
    @Override
    public Information searchConfessionWall(OvSearchConfessionWall searchConfessionWall) {
        return null;
    }
}
